'''
Created on Dec 5, 2010

@author: jackreilly
'''


from google.appengine.ext import db
from jettube.models import getFromJetKey, User

NAME_KEY = 'station_name'
OWNER_KEY = 'owner'
PUBLIC_KEY = 'public'
KEY_KEY = 'station_key'
REG_STATION_KEY = 'stationName'
REG_FB_FRIENDS_KEY = 'ids[]'
NSTATIONS = 100


class Station( db.Model ):
    name = db.StringProperty()
    public = db.BooleanProperty( default = True )
    owner = db.ReferenceProperty(User.User)
    
    
def createJetStation(name):
    owner = User.getMasterUser()
    public = True
    newStation = Station(name=name,owner=owner,key_name = generateKey(name, owner))
    newStation.public = public
    newStation.put()

def getUserStationsListFromUser(user):
    return createStationsListFromList(Station.all().filter('owner',user).fetch(NSTATIONS))
    
def getStationFromRequest(request):
    key = getFromJetKey(request, KEY_KEY)
    if not key:
        return getMasterStation()
    return Station.get(key)

def getStationsDictionaryForDropDownFromRequest(request):
    return getPublicStationsDict()

def getPublicStationsDict():
    return createStationsListFromList(Station.all().filter('public',True).fetch(NSTATIONS))
    
def createStationsListFromList(lst):
    return [{KEY_KEY:str(station.key()),
             NAME_KEY:str(station.name)} for station in lst]

def generateKey(name,owner):
    return '%s ::: %s' % (name,owner.key())

def getStationFromNameOwner(name,owner):
    return Station.get_by_key_name(generateKey(name, owner))


def registerNewStationFromRequest(request):
    owner = User.getUserFromKey(getFromJetKey(request, OWNER_KEY))
    stationName = getFromJetKey(request, REG_STATION_KEY)
    if not stationName:
        return False
    public = getFromJetKey(request, PUBLIC_KEY)
    if public == '0':
        public = False
    else:
        public = True
    station = Station.get_by_key_name(generateKey(stationName, owner, ))
    if station:
        return False
    station = Station(key_name=generateKey(stationName, owner),name=stationName,owner=owner,public=public)
    station.put()
    owner.addToStations(station)
    fbFriends = request.get_all(REG_FB_FRIENDS_KEY)
    map(lambda fbFriend: addFBFriendToStationWithID(station,fbFriend),fbFriends)
    return station
    
    
def stationKeyToDict(stationKey):
    station = Station.get(stationKey)
    return {NAME_KEY:station.name,
            PUBLIC_KEY:str(station.public),
            OWNER_KEY:station.owner.toDict(),
            KEY_KEY:str(station.key())}
    
def addFBFriendToStationWithID(station,id):
    user = User.getUserFromIDAndType(id, 'facebook')
    user.addStationWithPermission(station)
    
    
    
def getMasterStation():
    name = 'JetTube'
    owner = User.getMasterUser()
    return getStationFromNameOwner(name, owner)
    
